var createError = require('http-errors'); // 错误处理
var express = require('express'); // web框架
var path = require('path'); // 路径处理
var cookieParser = require('cookie-parser'); // 解析cookie
var logger = require('morgan'); // 日志
const session = require('express-session'); // session
const redisStore = require('connect-redis')(session) // redis存储session

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
const userRouter = require('./routes/user');
const blogRouter = require('./routes/blog');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

//app.use(logger('dev')); // 日志
const ENV = process.env.NODE_ENV
if (ENV !== 'production') {
  // 开发环境 / 测试环境
  app.use(logger('dev'));
} else {
  // 线上环境
  const logFileName = path.join(__dirname, 'logs', 'access.log')
  const writeStream = fs.createWriteStream(logFileName, {
    flags: 'a'
  })
  app.use(logger('combined', {
    stream: writeStream
  }));
}

app.use(express.json()); // 解析json格式的请求体(解析后放到req.body中)
app.use(express.urlencoded({ extended: false })); // 解析xxx-form 表单格式的请求体（不是json格式 解析后放到req.body中）
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 自动设置session，给前端set-cookie
// connect.sid=s%3AkMzKALHn0pXNUvQx0qqd6YKlx4WFLHZU.QStzfA6CpaksMMm1kPFzaG%2BkjdIJA1SWmf7023Jid80; Path=/; Expires=Sun, 20 Oct 2024 06:54:07 GMT; HttpOnly
const redisClient = require('./db/redis')
const sessionStore = new redisStore({
  client: redisClient
})
app.use(session({
  secret: 'lzq',
  resave: false,
  saveUninitialized: true,
  cookie: { 
    path: '/',
    httpOnly: true,
    maxAge: 1000 * 60 * 60 * 24
   },
   store: sessionStore
}))

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api/user', userRouter);
app.use('/api/blog', blogRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
